<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class user extends a_base {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        $data['userrank'] = $this->m_public->getAllInfo('userrank');

        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $condition = array(
            'from' => 'user'
        );
        $cnt = $this->m_public->get_list_count($condition);
        $cnt = $cnt['cnt'];
        $page_size = 20;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;
        $data['pagination'] = new pagination($arr);
        $condition1 = array(
            'from' => 'user',
            'limit' => $page_size,
            'offset' => $start_page,
            'join' => array(
                'userrank' => 'user.userrankid=userrank.userrankid'
            ),
            'column' => 'user.*,userrank.userrankname'
        );
        $data['list'] = $this->m_public->get_list($condition1);

        $this->load->view('user/index', $data);
    }

    public function user_add($userid){
        $data['userrank'] = $this->m_public->getAllInfo('userrank');
        if($userid){
            $data['info'] = $this->m_public->getRowInfo('user',array('userid'=>$userid));
        }else{
            $data['info'] = array();
        }
        $this->load->view('user/user_add',$data);
    }

    public function user_action($userid){
        $post = $this->input->post();
        if($post['userpass'] != ''){
            $post['userpass'] = md5($post['userpass']);
        }
        if($userid){
            $this->m_public->editInfo(array('userid'=>$userid),$post,'user');
        }else{
            $post['addtime'] = date('Y-m-d H:i:s',time());
            $this->m_public->addRowInfo('user',$post);
        }
        redirect('user/index');
    }

    public function audit($url,$parmykey,$table,$val,$ids)
    {
        if(!$ids){
            redirect(b_url("user/$url"));
        }
        $idArr = explode('.', $ids);
        foreach($idArr as $k=>$v){
            $data['isaudit'] = $val;
            $this->m_public->editInfo(array($parmykey=>$v),$data,$table);
        }
        redirect("user/$url");
    }

    public function user_add_import(){
        $data['userrank'] = $this->m_public->getAllInfo('userrank');
        $this->load->view('user/user_add_import',$data);
    }

    public function user_add_action(){
        $post = $this->input->post();
        $file_path = $post['upfile'];
        $path = getcwd().$file_path;
        $this->operate_file($path,$post['userrankid']);
        redirect('user/index');
    }

    private function operate_file($filePath,$userrankid){
        include_once('/static/bk/phpexcel/PHPExcel.php');
        //建立reader对象
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new PHPExcel_Reader_Excel5();
            if(!$PHPReader->canRead($filePath)){
                echo 'no Excel';
                return ;
            }
        }
        //建立excel对象，此时你即可以通过excel对象读取文件，也可以通过它写入文件
        $PHPExcel = $PHPReader->load($filePath);
        /**读取excel文件中的第一个工作表*/
        $currentSheet = $PHPExcel->getSheet(0);
        /**取得最大的列号*/
        $allColumn = $currentSheet->getHighestColumn();
        /**取得一共有多少行*/
        $allRow = $currentSheet->getHighestRow();
        //循环读取每个单元格的内容。注意行从1开始，列从A开始
        for($rowIndex=1;$rowIndex<=$allRow;$rowIndex++){
            if($rowIndex!=1){
                $data = array();
                for($colIndex='A';$colIndex<=$allColumn;$colIndex++){
                    $addr = $colIndex.$rowIndex;
                    $cell = $currentSheet->getCell($addr)->getValue();
                    if($cell instanceof PHPExcel_RichText)     //富文本转换字符串
                        $cell = $cell->__toString();
                    if($cell == null)
                        $cell = '';
                    switch ($colIndex) {
                        case 'A':
                            $key = 'username';
                            break;

                        case 'B':
                            $key = 'userpass';
                            break;

                        case 'C':
                            $key = 'realname';
                            break;

                        case 'D':
                            $key = 'sex';
                            break;

                        case 'E':
                            $key = 'email';
                            break;

                        case 'F':
                            $key = 'tel';
                            break;

                        case 'G':
                            $key = 'mobile';
                            break;

                        case 'H':
                            $key = 'address';
                            break;

                        case 'I':
                            $key = 'point';
                            break;

                        case 'J':
                            $key = 'comment';
                            break;

                        default:
                            # code...
                            break;
                    }
                    if($key!=''){
                        $data[$rowIndex][$key] = $cell;
                        $data[$rowIndex]['userrankid'] = $userrankid;
                    }else{
                        exit;
                    }
                }
                foreach($data as $val){
                    $this->m_public->addRowInfo('user',$val);
                }
            }
        }
        /*
        include_once('/static/bk/phpexcel/PHPExcel.php');
        include_once('/static/bk/phpexcel/PHPExcel/IOFactory.php');
        include_once('/static/bk/phpexcel/PHPExcel/Writer/Excel5.php');
        $objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
        $objPHPExcel = $objReader->load($path);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();           //取得总行数
        $highestColumn = $sheet->getHighestColumn(); //取得总列数

        // 第二种方法
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        echo 'highestRow='.$highestRow;
        echo "<br>";
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
        echo 'highestColumnIndex='.$highestColumnIndex;
        echo "<br>";
        $headtitle=array();
        for ($row = 1;$row <= $highestRow;$row++)
        {
            $strs=array();
            //注意highestColumnIndex的列数索引从0开始
            for ($col = 0;$col < $highestColumnIndex;$col++)
            {
                $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }
            $sql = "INSERT INTO te(`1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, `10`) VALUES (
            '{$strs[0]}',
            '{$strs[1]}',
            '{$strs[2]}',
            '{$strs[3]}',
            '{$strs[4]}',
            '{$strs[5]}',
            '{$strs[6]}',
            '{$strs[7]}',
            '{$strs[8]}',
            '{$strs[9]}',
            '{$strs[10]}')";
            echo $sql;
        }*/
    }

    public function user_export(){
        include_once('/static/bk/phpexcel/PHPExcel.php');
        include_once('/static/bk/phpexcel/PHPExcel/Writer/Excel2007.php');
        $filename = 'users-'.time();
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setCellValue('A1','用户名');
        $objPHPExcel->getActiveSheet()->setCellValue('B1','姓名');
        $objPHPExcel->getActiveSheet()->setCellValue('C1','性别');
        $objPHPExcel->getActiveSheet()->setCellValue('D1','邮件地址');
        $objPHPExcel->getActiveSheet()->setCellValue('E1','联系电话');
        $objPHPExcel->getActiveSheet()->setCellValue('F1','手机');
        $objPHPExcel->getActiveSheet()->setCellValue('G1','联系地址');
        $objPHPExcel->getActiveSheet()->setCellValue('H1','积分');
        $objPHPExcel->getActiveSheet()->setCellValue('I1','备注');
        $datas = $this->m_public->getAllInfo('user',array(),'username,realname,sex,email,tel,mobile,address,point,comment');
        $i = 2;
        foreach($datas as $val){
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$i,$val['username']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.$i,$val['realname']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.$i,$val['sex']);
            $objPHPExcel->getActiveSheet()->setCellValue('D'.$i,$val['email']);
            $objPHPExcel->getActiveSheet()->setCellValue('E'.$i,$val['tel']);
            $objPHPExcel->getActiveSheet()->setCellValue('F'.$i,$val['mobile']);
            $objPHPExcel->getActiveSheet()->setCellValue('G'.$i,$val['address']);
            $objPHPExcel->getActiveSheet()->setCellValue('H'.$i,$val['point']);
            $objPHPExcel->getActiveSheet()->setCellValue('I'.$i,$val['comment']);
            $i++;
        }
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save(str_replace('.php', '.xls', __FILE__));
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");

    }

    public function user_email_export(){
        include_once('/static/bk/phpexcel/PHPExcel.php');
        include_once('/static/bk/phpexcel/PHPExcel/Writer/Excel2007.php');
        $filename = 'users-email-'.time();
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->getActiveSheet()->setCellValue('A1','用户名');
        $objPHPExcel->getActiveSheet()->setCellValue('B1','姓名');
        $objPHPExcel->getActiveSheet()->setCellValue('C1','邮件地址');
        $datas = $this->m_public->getAllInfo('user',array(),'username,realname,email');
        $i = 2;
        foreach($datas as $val){
            $objPHPExcel->getActiveSheet()->setCellValue('A'.$i,$val['username']);
            $objPHPExcel->getActiveSheet()->setCellValue('B'.$i,$val['realname']);
            $objPHPExcel->getActiveSheet()->setCellValue('C'.$i,$val['email']);
            $i++;
        }
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter->save(str_replace('.php', '.xls', __FILE__));
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");
    }

    public function userrank(){
        $userrankname = $this->input->post('userrankname');
        $isclose = $this->input->post('isclose');
        $where = array();
        if($userrankname){
            $where['userrankname'] = $userrankname;
        }
        if($isclose != false){
            $where['isclose'] = $isclose;
        }
        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $condition = array(
            'from' => 'userrank',
            'where' => $where,
        );
        $cnt = $this->m_public->get_list_count($condition);
        $cnt = $cnt['cnt'];
        $page_size = 20;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;
        $data['pagination'] = new pagination($arr);

        $where1 = array();
        if($userrankname){
            $where1['u.userrankname'] = $userrankname;
        }
        if($isclose!='-1'){
            $where1['u.isclose'] = $isclose;
        }
        $condition1 = array(
            'from' => 'userrank as u',
            'where' => $where1,
            'limit' => $page_size,
            'offset' => $start_page,
            'order' => 'u.listid',
            'join' => array(
                'admin as a' => 'a.adminid=u.adminid'
            ),
            'column' => 'u.*,a.adminname',
        );
        if(!empty($where) || $isclose == '-1'){
            $data['is_filter'] = 1;
        }else{
            $data['is_filter'] = 0;
        }
        $data['list'] = $this->m_public->get_list($condition1);

        $this->load->view('user/userrank',$data);
    }

    public function userrank_add($userrankid){
        if($userrankid){
            $data['info'] = $this->m_public->getRowInfo('userrank',array('userrankid'=>$userrankid));
        }else{
            $data = array();
        }
        $this->load->view('user/userrank_add',$data);
    }

    public function userrank_action($userrankid){
        $post = $this->input->post();
        if($userrankid){
            $this->m_public->editInfo(array('userrankid'=>$userrankid),$post,'userrank');
        }else{
            $post['addtime'] = date('Y-m-d H:i:s',time());
            $post['adminid'] = $this->session->userdata['user_id'];
            $this->m_public->addRowInfo('userrank',$post);
        }
        redirect('user/userrank');
    }

    public function userlog(){
        $post = $this->input->post();
        $where = array();
        if($post != false){
            $flag = false;
            foreach($post as $key=>$val){
                if($val != ''){
                    if($key == 'username'){
                        $userInfo = $this->m_public->getRowInfo('user',array('username'=>$val),'userid');
                        $where['log.userid'] = $userInfo['userid'];
                    }else{
                        $where['log.'.$key] = $val;
                    }
                }
            }
        }
        $page = $this->input->get('page'); //当前页
        $page = intval($page);
        if ($page < 1) {
            $page = 1;
        }
        $condition = array(
            'from' => 'userlog as log',
            'where'=>$where,
        );
        $cnt = $this->m_public->get_list_count($condition);
        $cnt = $cnt['cnt'];
        $page_size = 20;
        $arr = array(
            'page' => $page, //当前页
            'page_size' => $page_size, //分页总大小
            'total' => $cnt//总记录数
        );
        $start_page = ($page - 1) * $page_size;
        $data['pagination'] = new pagination($arr);
        $condition1 = array(
            'from' => 'userlog as log',
            'limit' => $page_size,
            'offset' => $start_page,
            'join' => array(
                'user as user' => 'user.userid=log.userid'
            ),
            'where' => $where,
            'field' => 'log.*,user.username,user.realname',
        );
        if(!empty($where)){
            $data['filter'] = 1;
        }else{
            $data['filter'] = 0;
        }
        $data['list'] = $this->m_public->get_list($condition1);

        $this->load->view('user/userlog',$data);
    }

    public function delete_info($url,$parmykey,$table,$ids)
    {
        if(!$ids){
            redirect("user/$url");
        }
        $idArr = explode('.', $ids);
        foreach($idArr as $k=>$v){
            $res = $this->m_public->delInfo($table,array($parmykey=>$v));
        }
        redirect("user/$url");
    }

    public function edit_close($url,$parmykey,$table,$val,$ids)
    {
        if(!$ids){
            redirect(b_url("user/$url"));
        }
        $idArr = explode('.', $ids);
        foreach($idArr as $k=>$v){
            $data['isclose'] = $val;
            $this->m_public->editInfo(array($parmykey=>$v),$data,$table);
        }
        redirect("user/$url");
    }

}
